package com.miot.domain.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.NameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @Author: zhangyanbin
 * @Date: 2019/1/27 18:11
 * @Version 1.0
 */
public class MIDeviceUtil {

    protected static Logger logger = LoggerFactory.getLogger(MIDeviceUtil.class);

    /**
     * 获取设备列表 GET
     */
    public static final String MI_GET_DEVICE_LIST = "/bridge/controlunit/devices";
    /**
     * 获取设备的属性值 GET
     */
    public static final String MI_GET_PROPERTIES_LIST = "/bridge/controlunit/properties";
    /**
     * 设置属性值 POST
     */
    public static final String MI_SET_PROPERTIES = "/bridge/controlunit/properties";
    /**
     * 给设备重命名 POST
     */
    public static final String MI_DEVICE_RENAME = "/bridge/controlunit/rename";
    /**
     * 电视登录 POST
     */
    public static final String MI_TV_LOGIN = "/bridge/controlunit/tvlogin";
    /**
     * 解绑设备 POST
     */
    public static final String MI_DEVICE_UNBIND = "/bridge/controlunit/unbind";

    /**
     * 根据房间controlUnitId获取设备列表
     *
     * @param controlUnitId
     * @return
     */
    public static JSONArray getDeviceList(long controlUnitId) {
        try {
            String url = ControlUnitUtil.URI + MIDeviceUtil.MI_GET_DEVICE_LIST;
            String uri = MIDeviceUtil.MI_GET_DEVICE_LIST;
            return ControlUnitUtil.getListByControlUnitId(controlUnitId, url, uri, "getDeviceList");
        } catch (Exception e) {
            logger.error("接口getDeviceList获取设备列表错误信息是->", e.getMessage());
        }
        return new JSONArray();
    }

    /**
     * @param controlUnitId
     * @param did
     * @param deviceName
     */
    public static void deviceRename(Long controlUnitId, String did, String deviceName) {
        try {
            String url = ControlUnitUtil.URI + MIDeviceUtil.MI_DEVICE_RENAME;
            JSONObject dataValueJson = new JSONObject();
            dataValueJson.put("controlUnitId", controlUnitId);
            dataValueJson.put("compact", false);
            dataValueJson.put("did", did);
            dataValueJson.put("name", deviceName);
            List<NameValuePair> params = ControlUnitUtil.createParams(ControlUnitUtil.POST_METHOD, MIDeviceUtil.MI_DEVICE_RENAME, dataValueJson.toString());
            String sendPost = HttpUtils.sendPost(url, params);
            logger.info("修改设备接口返回值信息={}", sendPost);
        } catch (Exception e) {
            logger.error("小米重命名接口返回错误信息={}", e.getMessage());
        }

    }

    /**
     * 电视登录
     *
     * @param controlUnitId
     * @param TVUrl
     * @return
     */
    public static String tvLogin(long controlUnitId, String TVUrl) {
        try {
            String url = ControlUnitUtil.URI + MIDeviceUtil.MI_TV_LOGIN;
            JSONObject dataValueJson = new JSONObject();
            dataValueJson.put("controlUnitId", controlUnitId);
            dataValueJson.put("data", TVUrl);
            List<NameValuePair> params = ControlUnitUtil.createParams(ControlUnitUtil.POST_METHOD, MIDeviceUtil.MI_TV_LOGIN, dataValueJson.toString());
            String postResult = HttpUtils.sendPost(url, params);
            if (postResult == null) {
                return null;
            }
            String responseBody = JSONObject.parseObject(postResult).getJSONObject("data").getString("responseBody");
            return responseBody;
        } catch (Exception e) {
            logger.error("接口tvLogin：获取设备列表错误信息是->", e.getMessage());
        }
        return null;
    }

    /**
     * 解绑设备
     *
     * @param controlUnitId
     * @param realDid
     */
    public static void unbound(long controlUnitId, String realDid) {
        try {
            String url = ControlUnitUtil.URI + MIDeviceUtil.MI_DEVICE_UNBIND;
            JSONObject dataValueJson = new JSONObject();
            dataValueJson.put("controlUnitId", controlUnitId);
            dataValueJson.put("compact", false);
            dataValueJson.put("did", realDid);
            List<NameValuePair> params = ControlUnitUtil.createParams(ControlUnitUtil.POST_METHOD, MIDeviceUtil.MI_DEVICE_UNBIND, dataValueJson.toString());
            HttpUtils.sendPost(url, params);
        } catch (Exception e) {
            logger.error("接口unbound：设备解绑错误信息={}->", e.getMessage());
        }
    }

    /**
     * 设置设备属性接口
     *
     * @param properties
     * @param controlUnitId
     * @return
     */
    public static String setProperties(JSONArray properties, Long controlUnitId) {
        try {
            String url = ControlUnitUtil.URI + MIDeviceUtil.MI_SET_PROPERTIES;
            JSONObject finalJson = new JSONObject();
            finalJson.put("properties", properties);
            System.out.println(finalJson);
            String setPropertiesStr = Base64.encodeBase64URLSafeString(finalJson.toString().getBytes());
            JSONObject dataJSONObject = new JSONObject();
            dataJSONObject.put("controlUnitId", controlUnitId);
            dataJSONObject.put("properties", setPropertiesStr);
            List<NameValuePair> params = ControlUnitUtil.createParams(ControlUnitUtil.POST_METHOD, MIDeviceUtil.MI_SET_PROPERTIES, dataJSONObject.toString());
            String postResult = HttpUtils.sendPost(url, params);
            String responseBody = JSONObject.parseObject(postResult).getJSONObject("data").getString("responseBody");
            byte[] bytes = Base64.decodeBase64(responseBody);
            String propertyResult = new String(bytes);
            return propertyResult;
        } catch (Exception e) {
            logger.error("setProperties方法设置设备属性接口->{}", e.getMessage());
        }
        return null;
    }

    /**
     * 根据设备类型查询设备属性
     *
     * @param type
     * @return
     */
    public static JSONObject getPropertiesByType(String type) {
        String url = "https://miot-spec.org/miot-spec-v2/instance?type=" + type;
        String properties = HttpUtils.sendGet(url);
        return JSONObject.parseObject(properties);
    }
}
